<?php

namespace addons\prl\controller;
use think\addons\Controller;
use addons\prl\model\Channels as ChannelsModel;
use addons\prl\model\Viewsfields as ViewsfieldsModel;

class Base extends Controller
{

    //配置
    protected $config = '';

    //当前类型
    protected $view_type = 0;

    //当前栏目
    protected $current_channel = '';

    public function _initialize()
    {
        parent::_initialize();
        //获取配置
        $this->config = get_addon_config('cms');

        //判断栏目是否需要跳转
        if($this->current_channel->jump_child)
        {
            //子栏目信息
            $children_info = (new ChannelsModel)->channel()->channelorder()->where('pid', $this->current_channel->id)->find();
            //如果有子栏目信息 跳转到子栏目
            if(!empty($children_info))
            {
                return $this->redirect($children_info->href);
            }
        }

        $this->getViewsConfig();
        $this->assign('config', $this->config);
        $this->assign('channel_row', $this->current_channel);
    }

    /**
     * 重写fentch
     * @param  string $name 指定视图名称
     */
    protected function show($name = '')
    {
        $theme = empty($this->config['theme']) ? 'default' : $this->config['theme'];
        if(empty($name)){
            return $this->fetch($theme . '/' . $this->action);
        }
        //去除后缀
        if(strpos($name, ".html"))
            $name = substr($name, 0, strpos($name, ".html"));
        return $this->fetch($theme . '/'. $name);
    }

    protected function getViewsConfig()
    {
        $view_row = $this->current_channel->views($this->view_type)->find();
        if(empty($view_row)){
            $this->error(__('未绑定视图!'));
        }

        $fieldList = [];
        $fieldList = collection($view_row->viewsfields)->toArray();//绑定视图字段
        $fieldList = array_merge($fieldList, collection(ViewsfieldsModel::public()->select())->toArray());//绑定共有字段

        $fieldsIds = array_column($fieldList, 'id');//获取字段id
        $fieldsValue = collection($this->current_channel->viewsFieldsValue()->FieldsIds($fieldsIds)->select())->toArray();//获取到字段的值

        $list = [];
        foreach ($fieldList as $value) {
            if($value['common']){ //如果是私有的值
                $field_id = $value['id'];
                //查找栏目和字段的值相匹配的 并返回二维数组 如果没有 返回空数组
                $feild_value = array_filter($fieldsValue, function($r) use ($field_id){
                    return $r['viewsfields_id'] == $field_id;
                });
                //判断是否有值 如果有就赋值
                if (!empty($feild_value)) { 
                    $feild_value = array_merge($feild_value);
                    $value['value'] = $feild_value[0]['value'];
                }
            }

            //转化数据格式
            if (in_array($value['type'], ['select', 'selects', 'checkbox', 'radio'])) {
                $value['value'] = explode(',', $value['value']);
            }
            $list[$value['name']] = $value['value'];
        }
        $this->assign('view', $list);
    }
}
